package com.ffcs.cn.action.base.checkbox;

import com.ffcs.cn.DevelopProperties;


import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import java.awt.*;

/**
 * comboBox 多选时，需要在下拉按钮前面的框内显示多个数据项，每个数据项还得加关闭按钮，所以得开启编辑后重写Editor
 * 这里getEditorComponent返回了一个JScrollPane，是因为多个数据项被选择后，comboBox的框是有限的，会显示不全，有了JScrollPane，会出现水平滚动条，可以滑动查看
 * JScrollPane里放了一个panel，而panel里则是多个 PanelClose，PanelClose 渲染数据项并添加关闭按钮
 */
public class ComboBoxMultiSelectCloseEditor extends BasicComboBoxEditor {

	private final JScrollPane scroll;
	private final JPanel panel;

	public ComboBoxMultiSelectCloseEditor() {
		this.panel = new JPanel();
		this.panel.setBorder(BorderFactory.createEmptyBorder());
		this.panel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));
		this.scroll = new JScrollPane(this.panel);
		// 关闭垂直滚动条
		this.scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
		// 设置水平滚动条高度
		Dimension preferredSize = this.scroll.getHorizontalScrollBar().getPreferredSize();
		this.scroll.getHorizontalScrollBar().setPreferredSize(new Dimension(preferredSize.width, 2));
	}

	public void addPanelClose(PanelClose panelClose) {
		// 将带关闭按钮的渲染数据项的PanelClose添加到Panel
		this.panel.add(panelClose);
		this.panel.revalidate();
		this.panel.repaint();
	}

	/**
	 * 从Editor根据ComboBoxSelectableDataItem 移除PanelClose
	 * @param comboBoxSelectableDataItem 数据项
	 */
	public void removeComboBoxDataItem(ComboBoxSelectableDataItem comboBoxSelectableDataItem) {
		int count = this.panel.getComponentCount();
		for (int i = 0; i < count; i++) {
			PanelClose panelClose = (PanelClose)  this.panel.getComponent(i);
			if (panelClose.getComboBoxDataItem() == comboBoxSelectableDataItem) {
				this.panel.remove(i);
				this.panel.revalidate();
				this.panel.repaint();
				break;
			}
		}
	}

	public ComboBoxSelectableDataItem[] getComboBoxDataItems() {
		int count = this.panel.getComponentCount();
		ComboBoxSelectableDataItem[] comboBoxDataItems = new ComboBoxSelectableDataItem[count];
		for (int i = 0; i < count; i++) {
			PanelClose panelClose = (PanelClose)  this.panel.getComponent(i);
			comboBoxDataItems[i] = panelClose.getComboBoxDataItem();
		}
		return comboBoxDataItems;
	}


	@Override
	public Component getEditorComponent() {
		return this.scroll;
	}

}
